package com.blb.zy_community.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;

public class CodeUtils {
    // 验证码字符集
    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyz0123456789";
    // 验证码图片宽度
    private static final int WIDTH = 120;
    // 验证码图片高度
    private static final int HEIGHT = 48;
    // 验证码位数
    private static final int LENGTH = 4;

    // 生成随机验证码字符串
    public static String generateCaptcha() {
        StringBuilder captcha = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < LENGTH; i++) {
            int index = random.nextInt(CHARACTERS.length());
            captcha.append(CHARACTERS.charAt(index));
        }

        return captcha.toString();
    }

    // 绘制验证码图片并返回Base64编码的图片数据
    public static String generateImage(String captcha) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();

        // 设置背景颜色
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, WIDTH, HEIGHT);

        // 设置字体样式
        Font font = new Font("Arial", Font.BOLD, 36);
        graphics.setFont(font);

        // 绘制验证码字符
        for (int i = 0; i < LENGTH; i++) {
            Random random = new Random();
            int offsetX = 10 + random.nextInt(10);
            int offsetY = 30 + random.nextInt(10);
            graphics.setColor(getRandomColor());
            graphics.drawString(String.valueOf(captcha.charAt(i)), offsetX * i, offsetY);
        }

        // 释放资源
        graphics.dispose();

        // 将图片转为Base64编码的字符串并返回
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpeg", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(outputStream.toByteArray());
    }

    // 获取随机颜色
    private static Color getRandomColor() {
        Random random = new Random();
        return new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
    }
}
